package org.sklse.learningassistant.controller.resource.api;


import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.sklse.learningassistant.bean.resource.*;
import org.sklse.learningassistant.service.resource.*;
import org.sklse.learningassistant.util.TesseractUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/api/question")
public class QuestionApiController {

    @Autowired
    private Environment environment;

    @Autowired
    private QuestionService questionService;

    @ApiOperation(value = "根据题干查询试题", notes = "")
    @RequestMapping(value = "searchByText", method = RequestMethod.GET)
    public List<Question> searchByText(@RequestParam(value = "questionTitle") String questionTitle,
                                       @RequestParam(value = "pageNumber", defaultValue = "0", required = false) int pageNumber,
                                       @RequestParam(value = "pageSize", defaultValue = "5", required = false) int pageSize) throws IOException {
        return questionService.search(questionTitle,pageNumber,pageSize);
    }

    @RequestMapping(value = "add")
    public void add() throws IOException {
        questionService.add();
    }

    @RequestMapping(value = "findById")
    public Question findById(@RequestParam(value = "id")int id){
        return questionService.findById(id);
    }

    @ApiOperation(value = "根据base64查询试题", notes = "")
    @RequestMapping(value = "searchByBase64", method = RequestMethod.POST)
    @ResponseBody
    public Object searchByBase64(@RequestBody String base64DataJson) {
        try {
            String dataPrix = "";
            String data = "";
            String base64Data = (String) JSON.parseObject(base64DataJson).get("base64DataJson");
            if (base64Data == null || "".equals(base64Data)) {
                return "上传失败，上传图片数据为空";
            } else {
                String[] d = base64Data.split("base64,");
                if (d != null && d.length == 2) {
                    dataPrix = d[0];
                    data = d[1];
                } else {
                    return "上传失败，数据不合法";
                }
            }
            String suffix = "";
            if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
                suffix = ".jpg";
            } else if ("data:image/x-icon;".equalsIgnoreCase(dataPrix)) {
                suffix = ".ico";
            } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
                suffix = ".gif";
            } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
                suffix = ".png";
            } else {
                return "上传图片格式不合法";
            }
            String tempFileName = UUID.randomUUID().toString() + suffix;

            byte[] bs = Base64Utils.decodeFromString(data);
            try {
                String fileServerIndex = environment.getProperty("file.server.dir");
                String fullFilePath = fileServerIndex + tempFileName;
                FileUtils.writeByteArrayToFile(new File(fullFilePath), bs);
                String result = TesseractUtils.callTesseract(fullFilePath);
                System.out.println("图片识别结果");
                System.out.println(result);
                List<Question> questionList = searchByText(result,0,10);
                Map<String, Object> resultEntity = new HashMap<>();
                resultEntity.put("questionList", questionList);
                //TODO knowledgePoint List
                resultEntity.put("tesseractResult", result);

                return resultEntity;
            } catch (Exception e) {
                e.printStackTrace();
                return "上传失败，写入失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败";
        }
    }

}

